<template>
  <transition name="grimm-toast-fade">
    <grimm-popup
      type="toast"
      :z-index="zIndex"
      :mask="mask"
      v-show="isVisible"
      @mask-click="maskClick"
    >
      <i v-if="iconClass.length" class="grimm-toast-icon iconfont" :class="iconClass"></i>
      <div class="grimm-toast-tip" v-html="txt" v-show="txt"></div>
    </grimm-popup>
  </transition>
</template>
<script>
import GrimmPopup from '../Popup';
import visibilityMinxin from '../../common/mixins/visibility';
import popupMinxin from '../../common/mixins/popup';

const COMPONENT_NAME = 'grimm-toast';
const EVENT_TIMEOUT = 'timeout';

export default {
  name: COMPONENT_NAME,
  mixins: [visibilityMinxin, popupMinxin],
  props: {
    icon: {
      type: String,
      default: '',
    },
    mask: {
      type: Boolean,
      default: false,
    },
    txt: {
      type: String,
      default: '',
    },
    time: {
      type: Number,
      default: 3000,
    },
    zIndex: {
      type: Number,
      default: 100,
    },
    type: {
      type: String,
      default: '',
    },
  },
  computed: {
    iconClass() {
      const iconClass = [];
      if (this.icon) {
        iconClass.push(this.icon);
      }
      const classMap = {
        success: 'success',
        error: 'error-full',
        warning: 'tips',
      };
      const icon = classMap[this.type];
      if (icon) {
        iconClass.push(icon);
      }
      return iconClass;
    },
  },
  methods: {
    maskClick(e) {
      this.maskClosable && this.hide();
    },
    show() {
      this.isVisible = true;
      this.clearTimer();
      this.$nextTick(() => {
        if (this.time !== 0) {
          this.timer = setTimeout(() => {
            this.hide();
            this.$emit(EVENT_TIMEOUT);
          }, this.time);
        }
      });
    },
    hide() {
      this.isVisible = false;
      this.clearTimer();
    },
    clearTimer() {
      clearTimeout(this.timer);
      this.timer = null;
    },
  },
  components: {
    GrimmPopup,
  },
};
</script>
<style lang="stylus"  scoped>
@import '../../common/stylus/variable.styl';

.grimm-toast.grimm-popup {
  z-index: 99;
}

.grimm-toast >>> .grimm-popup-content {
  display: flex;
  align-items: center;
  padding: 13px 16px;
  color: $color-white;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: $radius-size-regular;
}

.grimm-toast-icon {
  margin-right: 5px;
}

.grimm-toast-tip {
  left: 20px;
  font-size: $fontsize-small;
  max-width: 12em;
  max-height: 40px;
  overflow: hidden;
}

.grimm-toast-fade-enter-active {
  animation: toastIn 0.2s;
}

.grimm-toast-fade-leave-active {
  animation: toastOut 0.2s;
}

@keyframes toastIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes toastOut {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}
</style>
